<?php

namespace App\Kuafu\CustomerCoupon\Jobs;

use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\CustomerCoupon\Model\SendCustomerCouponFailLog;
use App\Kuafu\CustomerCoupon\Service\CustomerCouponService;
use App\Kuafu\Wechat\Service\WechatSendMessageService;
use App\Library\FeiShu\SendFs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CustomerCouponExpireNotice implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    //任务名称-优惠券过期提醒
    const  QUEUE_NAME = '{RMS-USE-COUPON-EXPIRE-NOTICE}';

    private $tries = 40;
    private $userId;
    private $notice;
    private $endAt;
    private $shopId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $couponName, $start, $endAt, $notice, $shopId = 0)
    {
        $this->userId = $userId;
        $this->notice = $notice;
        $this->endAt  = $endAt;
        $this->shopId = $shopId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::channel('wechat')
           ->info('优惠券过期提醒进入队列：', ['userId' => $this->userId, 'notice' => $this->notice, 'shopId' => $this->shopId]);
        // 每次间隔5s，最大延迟≈3分钟
        if ($this->attempts() >= $this->tries) {
            Log::channel('wechat')->info('优惠券过期提醒失败：', ['userId' => $this->userId, 'notice' => $this->notice]);
            return;
        }
        if(empty($this->shopId)){
            $this->shopId = 0; // 强制给 0 兼容老的 小程序
        }
        //查询用户openId
        $platformId = 1;
        $userOpenId = CustomerPlatformService::getUserFieldByUserId($this->userId, $platformId, ['openid']);
        if ($userOpenId) {
            WechatSendMessageService::couponExpireNoticeSendMessage($this->notice, $this->endAt, $userOpenId->openid,
                $this->shopId);
        }
    }
}
